'use client'

import { useState, useEffect } from 'react'
import { useAuth } from '@/contexts/auth-context'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { Textarea } from '@/components/ui/textarea'
import { SessionManagement } from '@/components/profile/session-management'
import { 
  User, 
  Mail, 
  Lock, 
  Upload,
  Save,
  Eye,
  EyeOff,
  Monitor
} from 'lucide-react'

export function ProfileSettings() {
  const { user: authUser, loading: authLoading } = useAuth()
  const [showPassword, setShowPassword] = useState(false)
  const [isLoading, setIsLoading] = useState(false)
  const [message, setMessage] = useState<{ type: 'success' | 'error', text: string } | null>(null)

  const [formData, setFormData] = useState({
    name: '',
    email: '',
    bio: '',
    website: '',
    currentPassword: '',
    newPassword: '',
    confirmPassword: ''
  })

  useEffect(() => {
    if (!authLoading && authUser) {
      fetchUserProfile(authUser.id)
    }
  }, [authUser, authLoading])

  const fetchUserProfile = async (userId: string) => {
    try {
      const response = await fetch(`/api/profile?userId=${userId}`)
      const result = await response.json()

      if (response.ok) {
        const user = result.data
        setFormData(prev => ({
          ...prev,
          name: user.name || '',
          email: user.email || '',
          bio: user.bio || '',
          website: user.website || ''
        }))
      } else {
        // 使用认证用户的基本信息
        setFormData(prev => ({
          ...prev,
          name: authUser!.name || '',
          email: authUser!.email || ''
        }))
      }
    } catch (error) {
      console.error('获取用户资料失败:', error)
      // 使用认证用户的基本信息
      if (authUser) {
        setFormData(prev => ({
          ...prev,
          name: authUser.name || '',
          email: authUser.email || ''
        }))
      }
    }
  }

  const handleInputChange = (field: string, value: string) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  const handleSaveProfile = async () => {
    if (!authUser) {
      setMessage({
        type: 'error',
        text: '请先登录'
      })
      return
    }

    setIsLoading(true)
    setMessage(null)

    try {
      const response = await fetch('/api/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: authUser.id,
          name: formData.name,
          email: formData.email,
          bio: formData.bio,
          website: formData.website
        })
      })

      const result = await response.json()

      if (response.ok) {
        setMessage({
          type: 'success',
          text: '个人资料更新成功！'
        })
      } else {
        setMessage({
          type: 'error',
          text: result.error || '更新失败，请重试'
        })
      }
    } catch (error) {
      setMessage({
        type: 'error',
        text: '网络错误，请重试'
      })
    } finally {
      setIsLoading(false)
      setTimeout(() => setMessage(null), 3000)
    }
  }

  const handleChangePassword = async () => {
    if (formData.newPassword !== formData.confirmPassword) {
      setMessage({
        type: 'error',
        text: '新密码和确认密码不匹配'
      })
      return
    }

    if (formData.newPassword.length < 6) {
      setMessage({
        type: 'error',
        text: '密码长度至少6位'
      })
      return
    }

    setIsLoading(true)
    setMessage(null)

    try {
      const response = await fetch('/api/auth/change-password', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          currentPassword: formData.currentPassword,
          newPassword: formData.newPassword
        })
      })

      const result = await response.json()

      if (response.ok) {
        setMessage({
          type: 'success',
          text: '密码修改成功！'
        })

        // 清空密码字段
        setFormData(prev => ({
          ...prev,
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        }))
      } else {
        setMessage({
          type: 'error',
          text: result.error || '密码修改失败，请重试'
        })
      }
    } catch (error) {
      setMessage({
        type: 'error',
        text: '网络错误，请重试'
      })
    } finally {
      setIsLoading(false)
      setTimeout(() => setMessage(null), 3000)
    }
  }

  return (
    <div className="space-y-6">
      {/* 消息提示 */}
      {message && (
        <div className={`p-4 rounded-md ${
          message.type === 'success' 
            ? 'bg-green-50 text-green-700 border border-green-200' 
            : 'bg-red-50 text-red-700 border border-red-200'
        }`}>
          {message.text}
        </div>
      )}

      {/* 个人资料设置 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <User className="h-5 w-5" />
            个人资料
          </CardTitle>
          <CardDescription>
            更新您的个人信息和公开资料
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 头像上传 */}
          <div>
            <Label>头像</Label>
            <div className="flex items-center gap-4 mt-2">
              <div className="h-16 w-16 bg-gradient-to-br from-blue-50 to-indigo-100 rounded-full flex items-center justify-center">
                <User className="h-8 w-8 text-blue-400" />
              </div>
              <Button variant="outline" size="sm">
                <Upload className="h-4 w-4 mr-2" />
                上传头像
              </Button>
            </div>
          </div>

          {/* 姓名 */}
          <div>
            <Label htmlFor="name">姓名</Label>
            <Input
              id="name"
              value={formData.name}
              onChange={(e) => handleInputChange('name', e.target.value)}
              placeholder="请输入您的姓名"
            />
          </div>

          {/* 邮箱 */}
          <div>
            <Label htmlFor="email">邮箱</Label>
            <Input
              id="email"
              type="email"
              value={formData.email}
              onChange={(e) => handleInputChange('email', e.target.value)}
              placeholder="请输入您的邮箱"
            />
          </div>

          {/* 个人简介 */}
          <div>
            <Label htmlFor="bio">个人简介</Label>
            <Textarea
              id="bio"
              value={formData.bio}
              onChange={(e) => handleInputChange('bio', e.target.value)}
              placeholder="简单介绍一下自己..."
              rows={3}
            />
          </div>

          {/* 个人网站 */}
          <div>
            <Label htmlFor="website">个人网站</Label>
            <Input
              id="website"
              type="text"
              value={formData.website}
              onChange={(e) => handleInputChange('website', e.target.value)}
              placeholder="example.com 或 https://your-website.com"
            />
            <p className="text-xs text-gray-500 mt-1">
              可以输入域名（如 example.com）或完整网址，系统会自动添加 https:// 前缀
            </p>
          </div>

          <Button onClick={handleSaveProfile} disabled={isLoading}>
            <Save className="h-4 w-4 mr-2" />
            {isLoading ? '保存中...' : '保存资料'}
          </Button>
        </CardContent>
      </Card>

      {/* 密码设置 */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center">
            <Lock className="h-5 w-5 mr-2" />
            修改密码
          </CardTitle>
          <CardDescription>
            修改您的登录密码
          </CardDescription>
        </CardHeader>
        <CardContent className="space-y-4">
          {/* 当前密码 */}
          <div>
            <Label htmlFor="currentPassword">当前密码</Label>
            <div className="relative">
              <Input
                id="currentPassword"
                type={showPassword ? 'text' : 'password'}
                value={formData.currentPassword}
                onChange={(e) => handleInputChange('currentPassword', e.target.value)}
                placeholder="请输入当前密码"
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-0 top-0 h-full px-3"
                onClick={() => setShowPassword(!showPassword)}
              >
                {showPassword ? <EyeOff className="h-4 w-4" /> : <Eye className="h-4 w-4" />}
              </Button>
            </div>
          </div>

          {/* 新密码 */}
          <div>
            <Label htmlFor="newPassword">新密码</Label>
            <Input
              id="newPassword"
              type="password"
              value={formData.newPassword}
              onChange={(e) => handleInputChange('newPassword', e.target.value)}
              placeholder="请输入新密码（至少6位）"
            />
          </div>

          {/* 确认新密码 */}
          <div>
            <Label htmlFor="confirmPassword">确认新密码</Label>
            <Input
              id="confirmPassword"
              type="password"
              value={formData.confirmPassword}
              onChange={(e) => handleInputChange('confirmPassword', e.target.value)}
              placeholder="请再次输入新密码"
            />
          </div>

          <Button 
            onClick={handleChangePassword} 
            disabled={isLoading || !formData.currentPassword || !formData.newPassword}
          >
            <Lock className="h-4 w-4 mr-2" />
            {isLoading ? '修改中...' : '修改密码'}
          </Button>
        </CardContent>
      </Card>

      {/* 登录设备管理 */}
      <SessionManagement />
    </div>
  )
}
